#include <cjson/cJSON.h>
#include "seqiot.h"
#include "sqlite.h"
#include "param.h"
#include "sql_dml.h"
#include "cgi_helper.h"
#include "redis.h"

void usage(const char *arg0) {
    fprintf(stderr, "usage %s --method --query --body --help\n"
                    "\t--method <GET|POST>\n"
                    "\t--query table=<table_name>&key=<pk>\n"
                    "\t--body {id:0}\tjson format\n", arg0);
}

void json_output(const char *json) {
    fputs("Content-type:application/json\n\n", stdout);
    fputs(json, stdout);
    fflush(stdout);
}

void csv_output(sqlite3 *db, char *sql) {
    FILE *fp = stdout;
    fputs("Content-type:text/csv\n\n", fp);
    sql_execute_csv(db, sql);
    fflush(fp);
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        if (0 == strcmp("-?", argv[1]) || 0 == strcmp("--help", argv[1])) {
            usage(argv[0]);
            return EXIT_FAILURE;
        }
    }

    char filename[NAME_MAX];
    char *p = strrchr(argv[0], '/');
    snprintf(filename, sizeof(filename), "/etc/%s.db", p ? p + 1 : argv[0]);

    log_init();

    seqiot_t *seqiot = seqiot_new();
    read_config(seqiot, NULL, 0, -1);

    if (!redis_open(seqiot->local_address)) {
        return EXIT_FAILURE;
    }
    http_request_t request;
    bzero(&request, sizeof(request));
    request.request_method = HTTP_METHOD_GET;
    http_request_from_args(&request, argc, argv);
    http_request_from_env(&request);

    query_param_t param;
    bzero(&param, sizeof(param));
    param_parse_query(&param, request.query_string);

    char sql[1024] = {};
    if (!strcasecmp(HTTP_METHOD_GET, request.request_method)) {
        sqlite3 *db = sqlite_open_read(filename);
        if (NULL == db) {
            fprintf(stderr, "can't open sqlite file: %s\n", filename);
            return EXIT_FAILURE;
        }
        param_to_sql_get(&param, sql, sizeof(sql));
        const char *table = param_get_table(&param);
        if (0 == strcasecmp("acquire", table)) {
            csv_output(db, sql);
        } else {
            const char *method = param_get_method(&param);
            if (0 == strcasecmp("csv", method)) {
                csv_output(db, sql);
            } else {
                if (0 == strcasecmp("info", method)) { /*实时tsdb采集信息上报*/
                    request.json = acquire_info_func(seqiot);
                } else
                    request.json = sql_execute(db, sql);
                const char *json = cJSON_Print(request.json);
                json_output(json);
            }
        }
        sqlite3_close(db);
    } else if (!strcasecmp(HTTP_METHOD_POST, request.request_method)) {
        http_request_from_file(&request, stdin);
        sqlite3 *db = sqlite_open(filename);
        if (NULL == db) {
            fprintf(stderr, "can't open sqlite file: %s\n", filename);
            return EXIT_FAILURE;
        }
        param_parse_cjson(&param, request.json);
        param_to_sql_post(&param, sql, sizeof(sql));
        request.json = sql_post_execute(db, sql);
        const char *json = cJSON_Print(request.json);
        json_output(json);
        sqlite3_close(db);
    }
    log_debug("execute finished");

    cJSON_Delete(request.json);

    redis_close();

    seqiot_free(seqiot);

    log_fini();

    return EXIT_SUCCESS;
}